<?php

namespace app\web\controller;

use app\common\cachemodel\AppQq;
use app\common\cachemodel\Recode as RecodeCacheModel;
use app\common\cachemodel\Wechat;
use app\common\cachemodel\ZlRecordShareAdd;
use app\common\lib\astrolog\Astrolog;
use app\common\lib\exception\ApiException;
use app\common\lib\Push;
use app\common\lib\Util;
use app\common\model\MessageCenter;
use app\common\model\Recode;
use app\common\model\User;
use GuzzleHttp\Exception\GuzzleException;
use \think\Controller;
use \app\common\lib\Jssdk;
use think\Db;
use \think\Env;
use app\common\lib\Aes;
use app\common\lib\IAuth;
use think\Exception;
use think\Log;
use think\response\Json;

/**
 * 邀请输入档案信息H5页面
 * Class InvitateInputRecord
 * @package app\web\controller
 */
class InvitateInputRecord extends Controller
{
    protected $noNeedJudgeSummer = ['香港特别行政区', '澳门特别行政区', '台湾省', '北美洲', '大洋洲', '非洲', '南美洲', '欧洲', '亚洲', ''];
    protected $setting = [
        'natal' => [
            'planet' => [
                [1, 8.5], [1, 7.5], [1, 3.5], [1, 3.5], [1, 4], [1, 4.5], [1, 4.5], [1, 2.5], [1, 2.5], [1, 2.5],
                [0, 0], [0, 0], [0, 0], [0, 0], [1, 2.5], [0, 0], [0, 0], [1, 2.5], [1, 2.5], [1, 2.5], [1, 2.5]
            ],
            'phase' => [
                0 => [0, 1], 60 => [1, 0], 90 => [1, 0], 120 => [1, 0], 180 => [1, 0],
                45 => [0, 0], 135 => [0, 0], 30 => [0, 0], 150 => [0, 0], 72 => [0, 0], 144 => [0, 0]
            ],
            'arabic' => [
                [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
                [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],
                [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]
            ],
            'h_sys' => 'p',
            'firdaria' => 'default',
            'bound_type' => 'default',
            'ecliptic' => 0,
            'profection_push_direction' => 0,
            'decanates' => 0,
            'ayanamsa' => 0,
            'location_use' => 0
        ],
    ];

    private $oss = '';
    //微信分享图片
    protected $share_img = '';

    protected $LOG_PRE = '邀请添加档案web错误：';

    public function _initialize(): void
    {
        $this->oss = Env::get('host.photo');
        $this->share_img = $this->oss . 'web/invitate_input_record/images/share_logo.png';
    }

    /**
     * 微信/qq档案邀请-填写档案信息页面
     * @return mixed|Json
     * @throws \Exception
     */
    public function add()
    {

        $isTest = false;//是否测试

        if ($isTest)
        {
            //qq //dev Mark （手机号注册的）
            //http://192.168.0.193/web/invitate_input_record/add?token=LYpC8C8OjoGUKVze0MO95HDZXNYc+hZJOxHmkUizJ4fj6SDtMW5UM1uW/64VFZHq


//            $uid = '10834769';//beta dis Mark（手机号注册的）
            $uid = '10254602';//dev Mark （手机号注册的）//http://wechat.goddessxzns.com/web/invitate_input_record/add?token=SDtJSHeqkFL71wFUmrZ9We5xoO/qtg8DAEWe0lEzxKBEbXXNjViAoASMUTiBylIU
            //-----dev test123（mark微信小号 注册的）----
//            $uid = '10252243';//http://wechat.goddessxzns.com/web/invitate_input_record/add?token=SDtJSHeqkFL71wFUmrZ9We5xoO/qtg8DAEWe0lEzxKBEbXXNjViAoASMUTiBylIU
//            array (
//                'uid' => '10252243',
//                'openid' => 'oyHls1jqTMBSnu07TyJrhAQxmeW4',
//                'create_time' => '1528296520',
//                'country' => '中国',
//                'sex' => '1',
//                'unionid' => 'oIVMdt6dAMCXvo_N7RTyleYENjZg',
//                'city' => '沧州',
//                'access_token' => '10_pltGCzuQDPrwKItPVikB5NEU-wX1IuKAMKcR17qHRvjAaIF2GbdTLUmMmj2akfCIbP6QIlcTyaabeQSiN-XZqI5ZS8elOVSw9RyKh6QZ8gc',
//                'expires_in' => '1528303720',
//                'refresh_token' => '10_ZgGo3GfbSeTVZJytMKsfI1vacorgvnAqwTK1gBgCzvmChDFcNgUmes3pRnNMXqk3LpBIUCQ68dcpZMfmkC6er63Kk7APBZyn9uVR3uX3oMw',
//                'province' => '河北',
//                'nickname' => '逍遥十四少',
//                'scope' => 'snsapi_userinfo',
//                'headimgurl' => 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJAzDhj0L8vLc6rmPVOiaT1LYOW2ncpgBIicXq1OB7fia00lZeCjOsvJW14dbeY5Z7zdEeUxs5D4cI3Q/132',
//            )
            //-----dev test123（mark微信小号 注册的）----
            session('love.unionid', 'oIVMdt6dAMCXvo_N7RTyleYENjZg');
            session('love.name', 'mark');
            session('love.headimgurl', 'http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoc4vMM9X5giczROtmmdKIZWCtp0EyoNibLZ6AkKMlRPibKYzxcicghWucLZHehD4StFTSAauGTq86PZw/132');
            session('love.sex', '2');
            $params['uid'] = $uid;
            $params['timestamp'] = 1574127661;
            $params['share_to'] = 1;//【1：微信；2：qq】
            $status = 0;//0：填写信息；1：已填写；2：提交成功；3：自己邀请自己，提示错误；4：请从qq或者微信打开；【这里只能输入1/2】
            $is_user_have_record = 1;//根据uniond查询这个用户是否已经存在档案；0：不存在；1：已存在；
            if ($is_user_have_record)
            {//如果有，那么把用户的信息，传到h5里去
                $record = [
                    'uid' => $uid,
                    'name' => 'test',
                    'sex' => 1,
                    'year' => 1989,
                    'month' => 10,
                    'day' => 24,
                    'hour' => 12,
                    'minute' => 0,
                    'timezone' => 8,
                    'birth_country' => '河北省',
                    'birth_province' => '沧州市',
                    'birth_city' => '河间市',
                    'live_country' => '内蒙古自治区',
                    'live_province' => '呼和浩特市',
                    'live_city' => '新城区',
                    'comments' => '自己',
                    'isself' => 1,
                    'long_deg' => 116,
                    'long_min' => 25,
                    'ew' => 1,
                    'lat_deg' => 39,
                    'lat_min' => 55,
                    'ns' => 1,
                    'avatar' => '/uploads/avatar/20190703/1e0a5fa0253947e8411129c34892d620.png'
                ];
            }
        } else
        {
            $token_param = input('token/s', '');
            $isEncode = input('is_encode/d', 0);
            if (!$isEncode)
            {
                $token = urldecode($token_param);
                //把空格替换成“+”
                $token = str_replace(' ', '+', $token);
            } elseif ($isEncode === 2)
            {
                $token = base64_decode($token_param, true);
            } else
            {
                $token = $token_param;
            }
            // access-token AES解密
            $str = (new Aes())->decryptWithOpenssl($token);
            if (empty($str))
            {
                throw new ApiException($this->LOG_PRE . '参数错误');
            }

            parse_str($str, $params);
            //检查session，如果不存在，那么就直接跳转到登录
            $this->checkLogin($token_param, $params['share_to'], $isEncode);
        }

        //检查输入参数是否正确
        if (!isset($params['uid']))
        {
            throw new ApiException($this->LOG_PRE . 'uid参数为空');
        }
        if (!isset($params['timestamp']))
        {
            throw new ApiException($this->LOG_PRE . 'timestamp参数为空');
        }
        if (!isset($params['share_to']))
        {
            throw new ApiException($this->LOG_PRE . 'share_to参数为空');
        }
        if (isset($params['share_to']) && ($params['share_to'] * 1 !== 1 && $params['share_to'] * 1 !== 2))
        {
            throw new ApiException($this->LOG_PRE . 'share_to参数错误，只能为【1：微信；2：qq】，实际为' . $params['share_to']);
        }
        try
        {
            if (!$isTest)
            {
                $record = [
                    'uid' => '',
                    'name' => '',
                    'sex' => '',
                    'year' => '',
                    'month' => '',
                    'day' => '',
                    'hour' => '',
                    'minute' => '',
                    'timezone' => '',
                    'birth_country' => '',
                    'birth_province' => '',
                    'birth_city' => '',
                    'live_country' => '',
                    'live_province' => '',
                    'live_city' => '',
                    'comments' => '',
                    'isself' => '',
                    'long_deg' => '',
                    'long_min' => '',
                    'ew' => '',
                    'lat_deg' => '',
                    'lat_min' => '',
                    'ns' => '',
                    'avatar' => '',
                ];
                $is_user_have_record = 0;
                $signPackage = [];
            }
            $session_avatar = session('qq.headimgurl');
            $session_sex = session('qq.sex');
            $session_name = session('qq.name');
            $session_unionid = session('qq.unionid');
            if (1 === $params['share_to'] * 1)
            {
                $session_avatar = session('love.headimgurl');
                $session_sex = session('love.sex');
                $session_name = session('love.name');
                $session_unionid = session('love.unionid');
            }

            $data = [
                'uid' => $params['uid'],//用户id
                'status' => '0',//0：填写信息；1：已填写；2：提交成功；3：自己邀请自己，提示错误；4：请从qq或者微信打开；【这里只能输入1/2】
                'is_user_have_record' => 0,//根据unionid查询这个用户是否已经存在档案
                'inviter_name' => '',//邀请者的名字
                'share_to' => $params['share_to'],//【1：微信；2：qq】
                'signPackage' => $signPackage,//微信签名
                'unionid' => $session_unionid,
                'timestamp' => $params['timestamp'],
                'record' => $record
            ];

            $AppWechat = new Wechat();
            $AppQq = new AppQq();
            $Record = new Recode();

            //查询是邀请者自己点击进入的邀请h5，那么就直接提示错误
            if (1 === $params['share_to'] * 1)
            {//微信登录
                $wechat_info = $AppWechat->getWechatInfo($params['uid'], 2);
                if ($wechat_info && isset($wechat_info['unionid']) && $wechat_info['unionid'] === $session_unionid)
                {//用户绑定了微信，自己邀请了自己
                    $data['status'] = 3;
                }
            } else
            {
                //qq登录
                $qq_info = $AppQq->getUserQqInfoFromCache($params['uid'], 2);
                if ($qq_info && isset($qq_info['unionid']) && $qq_info['unionid'] === $session_unionid)
                {//用户绑定了qq，自己邀请了自己
                    $data['status'] = 3;
                }
            }

            if (!isset($data['status']) || (isset($data['status']) && 3 !== $data['status'] * 1))
            {
                //根据unionid查询这个用户，是否微信/qq注册过
                if (1 === $params['share_to'] * 1)
                {//微信登录
                    $appWechat = $AppWechat->getWechatInfo($session_unionid, 1);
                    if (isset($appWechat['uid']) && !$isTest)
                    {
                        //查询这个用户是否有自己的档案
                        $recordTemp = $Record->getSelfRecode($appWechat);
                        if ($recordTemp)
                        {
                            $record = $recordTemp;
                            $is_user_have_record = 1;
                        }
                    }
                } else
                {
                    //qq登录
                    $appQq = $AppQq->getUserQqInfoFromCache($session_unionid);
                    if (isset($appQq['uid']) && !$isTest)
                    {
                        $recordTemp = $Record->getSelfRecode($appQq);
                        if ($recordTemp)
                        {
                            $record = $recordTemp;
                            $is_user_have_record = 1;
                        }
                    }
                }

                $ZlRecordShareAdd = new ZlRecordShareAdd();
                $isUserInput = $ZlRecordShareAdd->hasAddRecord($params['share_to'], $session_unionid, $params['timestamp']);
                if ($isUserInput)
                {//查到了这个用户，需要提示用户已经填写过了
                    $status = 1;
                } else
                {//没有查到这个用户，需要用户填写
                    $status = 0;
                }
                //查询邀请者的名字
                $inviter = (new User())->getUserinfo(['id' => $params['uid']]);
                $inviter_name = $inviter['nickname'];

                //---数据处理---
                //替换type为sex
                if (isset($record['type']))
                {
                    $record['sex'] = $record['type'];
                }
                //替换avatar
                if (isset($record['avatar']))
                {
                    $avatar = $record['avatar'];
                    $preg = "/^http(s)?:\\/\\/.+/";
                    if (!preg_match($preg, $avatar))
                    {
                        $avatar_tmp = substr($avatar, 0, 1);
                        if ($avatar_tmp === '/')
                        {
                            $record['avatar'] = $this->oss . substr($avatar, 1, strlen($avatar));
                        } else
                        {
                            $record['avatar'] = $this->oss . $avatar;
                        }

                    }
                }
                //---数据处理---
                $data = [
                    'uid' => $params['uid'],//用户id
                    'status' => $status,//0：填写信息；1：已填写；2：提交成功；3：自己邀请自己，提示错误；4：请从qq或者微信打开；【这里只能输入1/2】
                    'record' => $record,
                    'is_user_have_record' => $is_user_have_record,//根据unionid查询这个用户是否已经存在档案
                    'inviter_name' => $inviter_name,//邀请者的名字
                    'share_to' => $params['share_to'],//【1：微信；2：qq】
                    'unionid' => $session_unionid,
                    'timestamp' => $params['timestamp'],
                ];
            }

            if (!$is_user_have_record)
            {//如果用户没有档案，那么就把头像、昵称、性别传过去
                $data['record']['avatar'] = $session_avatar;
                $data['record']['sex'] = $session_sex;
                $data['record']['name'] = $session_name;
            } else
            {
                try
                {
                    //如果用户有档案，获取用户的现居地和出生地，省市区的code
                    $locations = Astrolog::getInstance()->getLocations();
                    $item = $locations[$data['record']['birth_country'] . '-' . $data['record']['birth_province'] . '-' . $data['record']['birth_city']];
                    $data['record']['code_birth_country'] = $item['code_country'];
                    $data['record']['code_birth_province'] = $item['code_province'];
                    $data['record']['code_birth_city'] = $item['code_city'];

                    $item = $locations[$data['record']['live_country'] . '-' . $data['record']['live_province'] . '-' . $data['record']['live_city']];
                    $data['record']['code_live_country'] = $item['code_country'];
                    $data['record']['code_live_province'] = $item['code_province'];
                    $data['record']['code_live_city'] = $item['code_city'];
                }
                catch (\Exception $e)
                {
                    //用户有档案，但是【获取用户的现居地和出生地，省市区的code】出错
                    $data['record']['avatar'] = $session_avatar;
                    $data['record']['sex'] = $session_sex;
                    $data['record']['name'] = $session_name;
                }
            }
            if (1 === $params['share_to'] * 1)
            {
                //微信分享的获取微信js签名
                $signPackage = (new Jssdk())->getSignPackage();
            }


            //时间小于10，加0补充
            $data['record']['month'] = str_pad($data['record']['month'], 2, '0', STR_PAD_LEFT);
            $data['record']['day'] = str_pad($data['record']['day'], 2, '0', STR_PAD_LEFT);
            $data['record']['hour'] = str_pad($data['record']['hour'], 2, '0', STR_PAD_LEFT);
            $data['record']['minute'] = str_pad($data['record']['minute'], 2, '0', STR_PAD_LEFT);

            return $this->fetch('add', [
                'title' => '来准了填写你的档案信息，解密我们的亲密关系',//网页标题
                'share_title' => '来准了填写你的档案信息，解密我们的亲密关系',//微信分享标题
                'share_introduction' => '来准了告诉我下你的星盘配置，解密我们的性格构成和亲密关系',//微信分享内容
                'share_img' => $this->share_img,
                'signPackage' => $signPackage,//微信签名
                'data' => $data,//带过去的数据
                'oss' => $this->oss,
                'is_test' => $isTest,
            ]);
        }
        catch (\Exception $e)
        {
            throw new ApiException('[' . $e->getFile() . ':' . $e->getLine() . ']' . PHP_EOL . $this->LOG_PRE . '：[uid=' . $params['uid'] . '&timestamp=' . $params['timestamp'] . '&share_to=' . $params['share_to'] . ']' . $e->getMessage());
        }

    }

    /**
     * 个人信息保存
     * @return Json
     * @throws GuzzleException
     */
    public function save(): Json
    {
        //根据unionid查询这个用户是否已经存在档案；0：不存在；1：已存在；
        $is_user_have_record = input('is_user_have_record/d');
        $share_to = input('share_to/d');
        $timestamp = input('timestamp/d');
        $unionid = input('unionid/s', '', 'htmlspecialchars');// 档案名称;
        $uid = input('uid/d');//用户的id，此处是邀请者

        //检查输入参数是否正确
        if (empty($uid))
        {
            return show(config('code.error'), 'uid参数为空');
        }
        if (empty($timestamp))
        {
            return show(config('code.error'), 'timestamp参数为空');
        }
        if (empty($unionid))
        {
            return show(config('code.error'), 'unionid参数为空');
        }
        if (empty($share_to))
        {
            return show(config('code.error'), 'share_to参数为空');
        }
        if ($share_to * 1 !== 1 && $share_to * 1 !== 2)
        {
            return show(config('code.error'), 'share_to参数错误');
        }

        // 档案标签如 自己 朋友 案例
        $isself = 0;//input('isself/d');// 档案是否为自己 0 否 | 1 是（自己的档案无法删除，无法更改为其他标签）
        $comments = '朋友';//标签，默认为朋友

        $name = input('name/s', '', 'htmlspecialchars');// 档案名称
        $type = input('sex/d');// 档案类型  1男 | 2 女 | 3 男同 | 4 女同 | 5 事件 | 6 卜卦
        if (!$type)
        {
            return show(config('code.error'), '请选择性别！');
        }
        if (!in_array($type, [1, 2, 3, 4, 5, 6], true))
        {
            return show(config('code.error'), '性别异常，请重新选择性别');
        }
        $year = input('year/d');// 出生时间-年
        $month = input('month/d');// 出生时间-月
        $day = input('day/d');// 出生时间-日
        $hour = input('hour/d');// 出生时间-时
        $minute = input('minute/d');// 出生时间-分
        $timezone = input('timezone/d', 8);// 出生时间-时区
        $birth_country = input('birth_country/s', '', 'htmlspecialchars');// 出生地点-省
        $birth_province = input('birth_province/s', '', 'htmlspecialchars');// 出生地点-市
        $birth_city = input('birth_city/s', '', 'htmlspecialchars');// 出生地点-区
        $live_country = input('live_country/s', '', 'htmlspecialchars');// 现居地-省
        $live_province = input('live_province/s', '', 'htmlspecialchars');// 现居地-省
        $live_city = input('live_city/s', '', 'htmlspecialchars');// 现居地-省
        $long_deg = input('long_deg/d');// 经度-度
        $long_min = input('long_min/d');// 经度-分
        $ew = input('ew/d');// 东经|西经 1|-1
        $lat_deg = input('lat_deg/d');// 纬度-度
        $lat_min = input('lat_min/d');// 纬度-分
        $ns = input('ns/d');// 南纬北纬  1|-1
        $avatar = input('avatar/s', '', 'htmlspecialchars_decode');// 头像地址

        $is_summer = 0;
        // 只判断大陆地区的夏令时
        if (!in_array($birth_country, $this->noNeedJudgeSummer, true))
        {
            $is_summer = isSummerTime($hour, $minute, 0, $month, $day, $year) ? 1 : 0;// 是否开启夏令时
        }

        $data = [
            'uid' => $uid,
            'name' => $name,
            'type' => $type,
            'year' => $year,
            'month' => $month,
            'day' => $day,
            'hour' => $hour,
            'minute' => $minute,
            'timezone' => $timezone,
            'birth_country' => $birth_country,
            'birth_province' => $birth_province,
            'birth_city' => $birth_city,
            'live_country' => $live_country,
            'live_province' => $live_province,
            'live_city' => $live_city,
            'comments' => $comments,
            'isself' => $isself,
            'long_deg' => $long_deg,
            'long_min' => $long_min,
            'ew' => $ew,
            'lat_deg' => $lat_deg,
            'lat_min' => $lat_min,
            'ns' => $ns,
            'avatar' => $avatar,
            'is_summer' => $is_summer,
            'add_type' => 2,// 1自己创建 2朋友添加 3注册默认创建
            'is_read' => 0, // 是否已读 1已读 0未读
        ];
        $validate = validate('Recode');

        if (!$validate->scene('add')->check($data))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        try
        {
            if (!$is_user_have_record)
            {//头像是被邀请者，微信/qq授权获取的，需要上传到oss
                $avatarInfo = Util::wxImgUploadOss($avatar, 'uploads/avatar');
                $avatar = $avatarInfo['success'] ? $avatarInfo['url'] : $avatar;
                $data['avatar'] = $avatar;
            }

            // 查询当前星盘日月水金火木土等星落座落宫存入数据库
            $astro_data = Astrolog::getInstance()->setExecPrefix(config('astrolog.prefix'))
                ->setIsAstrolabe(false)
                ->setRecode1($data)
                ->setUserSetting($this->setting)
                ->getTheRecodeAstro();

            $RecodeCacheModel = new RecodeCacheModel();
            //插入档案信息
            $rid = $RecodeCacheModel->SaveData($uid, $data);
            if ($rid === false)
            {
                return json(['code' => 0, 'data' => [], 'msg' => '保存失败']);
            }

            if (!$rid)
            {
                return json(['code' => 10301, 'msg' => '操作失败']);
            }

            $astro_data['rid'] = $rid;
            $time = $this->request->time();
            $astro_data['create_time'] = $time;
            //档案附属表
            Db::table('app_recode_info')->insertGetId(['rid' => $rid, 'create_time' => $time, 'last_time' => $time]);// 新增当前档案访问数据
            //插入档案星盘数据
            $aid = Db::table('app_recode_astro')->insertGetId($astro_data);// 新增当前档案行星数据
            $data['id'] = $rid;
            $RecodeCacheModel->UpdateData($uid, $rid, ['aid' => $aid]);

            $record_share_add = [
                'uid' => $uid,
                'rid' => $rid,
//            'name' => $name, // 没有，用户使用第三方登录的时候，再去获取
                'type' => $share_to,
                'sex' => $type,
                'code' => $unionid,
                'time' => $timestamp,
                'year' => $year,
                'month' => $month,
                'day' => $day,
                'hour' => $hour,
                'minute' => $minute,
//            'timezone' => $timezone, 这里默认都是8
                'birth_country' => $birth_country,
                'birth_province' => $birth_province,
                'birth_city' => $birth_city,
                'live_country' => $live_country,
                'live_province' => $live_province,
                'live_city' => $live_city,
//            'comments' => $comments,
//            'isself' => $isself,
                'long_deg' => $long_deg,
                'long_min' => $long_min,
                'ew' => $ew,
                'lat_deg' => $lat_deg,
                'lat_min' => $lat_min,
                'ns' => $ns,
                'create_time' => $this->request->time()
//            'avatar' => $avatar, //没有，用户使用第三方登录的时候，再去获取
//            'is_summer' => $is_summer,
            ];
            $ZlRecordShareAdd = new ZlRecordShareAdd();
            $ZlRecordShareAdd->SaveData($record_share_add);
        }
        catch (\Exception $e)
        {
            Log::write('[' . $e->getFile() . ':' . $e->getLine() . ']' . PHP_EOL . $this->LOG_PRE . $e->getMessage() . PHP_EOL, 'error', true);
            return show(config('code.error'), '服务异常，请稍后重试！', []);
        }
        // 消息中心添加信息
        $messageData = [
            'status' => 0,
            'is_read' => 0,
            'range' => $uid,
            'type' => 2,
            'reid' => 0,
            'cid' => 0,
            'title' => '邀请好友添加档案',
            'content' => '添加好友档案完成，请查看',
            'link' => 'refresh_archives?need_auth=1',
            'target' => 'local',
            'create_time' => $this->request->time()
        ];
        //发送消息
        try
        {
            //推送消息
            (new Push())->pushUserMsg($uid, $messageData['content'], ['action' => 'refresh_archives'], $messageData['title']);
            //消息中心增加消息
            (new MessageCenter())->pushMessage($uid, $messageData);
            // 记录档案更新状态
            (new \app\common\cachemodel\Recode())->setUpdateStatus($uid);
        }
        catch (Exception $e)
        {
            Log::write('[' . $e->getFile() . ':' . $e->getLine() . ']' . PHP_EOL . $this->LOG_PRE . $e->getMessage() . PHP_EOL, 'error', true);
        }

        //查询邀请者的名字
        return show(config('code.success'), 'ok');
    }


    /**
     * 微信登陆
     */
    public function weixin_login(): void
    {
        $token = urlencode(input('get.token/s'));
        $isEncode = input('is_encode/d', 0);
        $appid = config('wechat.mp_appid');
        $domain = Env::get('host.domain');
        $redirect_uri = urlencode($domain . '/web/invitate_input_record/weixin_back' . '/is_encode/' . $isEncode);
        header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . $token . '#wechat_redirect');

        exit;
    }

    /**
     * 微信登陆返回
     */
    public function weixin_back(): void
    {
        $wechat_conf = config('wechat');
        $appid = $wechat_conf['mp_appid'];
        $appsecret = $wechat_conf['mp_secret'];
        $isEncode = input('is_encode/d', 0);

        $code = input('get.code/s');
        if (empty($code))
        {
            $this->error('微信授权失败！');
        }

        $token = urlencode(input('get.state/s'));
        if (empty($token))
        {
            $this->error('获取token失败！');
        }
        $access_token = session('love.access_token');
        if (empty($access_token) || $access_token === '')
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
            $access_token = json_decode(file_get_contents($access_token_url), false);
            if (isset($access_token->errcode))
            {
                $this->error('授权失败');
            }
            session('love.access_token', $access_token->access_token);
            session('love.refresh_token', $access_token->refresh_token);
            session('love.openid', $access_token->openid);
        }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . session('love.access_token') . '&openid=' . session('love.openid') . '&lang=zh_CN';
        $user_info = json_decode(file_get_contents($user_info_url), false);
        if (isset($user_info->errcode))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . session('love.refresh_token');
            $access_token = json_decode(file_get_contents($access_token_url), true);
            if (isset($access_token['access_token'], $access_token['refresh_token'], $access_token['openid']) && !empty($access_token))
            {
                session('love.access_token', $access_token['access_token']);
                session('love.refresh_token', $access_token['refresh_token']);
                session('love.openid', $access_token['openid']);

                $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token['access_token'] . '&openid=' . $access_token['openid'] . '&lang=zh_CN';
                $user_info = json_decode(file_get_contents($user_info_url), false);
                if (isset($user_info->errcode))
                {
                    echo '<h1>错误：</h1>' . $user_info->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
                    exit;
                }
            } else
            {//失败的话，重新授权登录
                if (40001 === $user_info->errcode)
                {//40001为invalid credential, access_token is invalid or not latest, hints: [ req_id: EfKfY24ce-3ItL5 ]，清空access_token
                    session('love.access_token', null);
                }
                $this->redirect('/web/invitate_input_record/weixin_login?token=' . $token . '&is_encode=' . $isEncode);
            }
        }
        //把unionid、headimgurl、name 保存到session里
        session('love.unionid', $user_info->unionid);
        session('love.headimgurl', $user_info->headimgurl);
        session('love.name', $user_info->nickname);
        session('love.sex', $user_info->sex);

        $this->redirect('/web/invitate_input_record/add?token=' . $token . '&is_encode=' . $isEncode);
    }


    /**
     * 检查session里是否有  unionid、headimgurl、name 这三个参数，如果为空，那么跳转到 微信 或者 qq 登录页面
     * @param string $token app邀请档案传过来的加密数据
     * @param int $share_to 【1：微信；2：qq】
     */
    private function checkLogin($token = '', $share_to = 1, $isEncode): void
    {
        if (1 === $share_to * 1 && (empty(session('love.unionid'))))
        {
            $this->redirect('/web/invitate_input_record/weixin_login?token=' . urlencode($token) . '&is_encode=' . $isEncode);
        } else if (2 === $share_to * 1 && (empty(session('qq.unionid')) || empty(session('qq.headimgurl')) || empty(session('qq.name'))))
        {
            $this->redirect('/web/invitate_input_record/qq?token=' . urlencode($token) . '&is_encode=' . $isEncode);
        }
    }


    public function qq(): void
    {
        $app_id = Env::get('qq.web_appid');
        $app_secret = Env::get('qq.web_appkey');
        $my_url = Env::get('qq.web_callback_url');
        $isEncode = input('is_encode/d', 0);

        //注  回调地址必须和该代码域名一致
        if (empty($_GET['code']))
        {//判断是否有code,若无code则去qq第三方接口请求授权
//            $_SESSION['state'] = md5(uniqid(rand(), true));//一串随机的字符串，用于回调时对比参数防止csrf攻击
            //拼接url地址同时url化回调地址并跳转
            $token = urlencode(input('get.token/s'));
            $url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=' . $app_id . '&redirect_uri=' . urlencode($my_url) . '&state=' .urlencode( $token . '|A|A|' . $isEncode);
            header('location: ' . $url);
        } else
        {
            $state = input('get.state/s');
            [$token, $isEncode] = explode('|A|A|', $state);
            //省略一步  使用state判断是否csrf攻击   使用$_SESSION['state']和$_GET['state']进行对比判断授权过程是否被劫持
            //拼接url地址使用code请求并获得access_token
            $url = 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=' . $app_id . '&client_secret='
                . $app_secret . '&code=' . $_GET['code'] . '&redirect_uri=' . $my_url;
            //发出请求
            $info = file_get_contents($url);
            //var_dump($info);由于传回来的数据是个字符串，不能直接使用，所以进行变量化
            $params = [];
            parse_str($info, $params);//把传回来的数据参数变量化
            //var_dump($params);变量化后的结果
            /*
             * array(3) {
             *  ["access_token"]=> string(32) "*********"  access_token
             *  ["expires_in"]=> string(7) "7776000"    access_token有效时间
             * ["refresh_token"]=> string(32) "****" }
             * */
            //判断access_token是否存在，如果不存在，那么让用户重新获取，例如：{"error":100019,"error_description":"code to access token error"}
            if (!isset($params['access_token']))
            {
                $this->redirect('/web/invitate_input_record/add?token=' . $token . '&is_encode=' . $isEncode);
            }

            //使用access_token去请求openid
            $graph_url = 'https://graph.qq.com/oauth2.0/me?access_token=' . $params['access_token'] . '&unionid=1';
            $str = file_get_contents($graph_url);
            //var_dump($str);  请求得到的结果
            //string(83) "callback( {"client_id":"*****","openid":"*****"} ); "
            //callback( {"client_id":"101255228","openid":"89F5D3BB8CEE2B386B02EAC397270E46","unionid":"UID_F3EEF816AB02F7B33521E87A5118B6FA"} );
            //由于得到的结果还是字符串且还不是json类型，只能手动截取json格式的数据
            //判断callback在字符串$str是否存在，如果存在则返回下标，否则false，下标不完全等于false，因为0会被判断为false
            if (strpos($str, 'callback') !== false)
            {
                $lpos = strpos($str, '(');//判断(出现的下标
                $rpos = strrpos($str, ')');//判断)出现的下标，加上r从右边开始查找
                $str = substr($str, $lpos + 1, $rpos - $lpos - 1);//截取字符串
                //从$rpos+1下标 { 处截取  $rpos - $lpos -1 位 ，此时$str的值就为一个json格式的数据了
                // {"client_id":"*****","openid":"*****"}
            }
            $user = json_decode($str, true);//json转对象,存放有返回的数据 client_id ，openid
            //拼接url并访问，用access_token和openid得到用户信息
            $urls = 'https://graph.qq.com/user/get_user_info?access_token=' . $params['access_token'] . '&oauth_consumer_key=' . $app_id . '&openid=' . $user['openid'];
            $rs = file_get_contents($urls);
            $ref = json_decode($rs, true);//得到的用户信息

            //把unionid、headimgurl、name 保存到session里
            session('qq.unionid', $user['unionid']);
            session('qq.headimgurl', $ref['figureurl_qq_1']??'');
            session('qq.name', $ref['nickname']??'');
            session('qq.sex', $ref['gender_type']);

            $this->redirect('/web/invitate_input_record/add?token=' . $token . '&is_encode=' . $isEncode);

//            stdClass::__set_state(array(
//                'ret' => 0,
//                'msg' => '',
//                'is_lost' => 0,
//                'nickname' => '我就是我',
//                'gender' => '男',
//                'gender_type' => 1,
//                'province' => '北京',
//                'city' => '东城',
//                'year' => '2009',
//                'constellation' => '',
//                'figureurl' => 'http://qzapp.qlogo.cn/qzapp/101423025/13034DA212A8AB518BADA60239C7D7F4/30',
//                'figureurl_1' => 'http://qzapp.qlogo.cn/qzapp/101423025/13034DA212A8AB518BADA60239C7D7F4/50',
//                'figureurl_2' => 'http://qzapp.qlogo.cn/qzapp/101423025/13034DA212A8AB518BADA60239C7D7F4/100',
//                'figureurl_qq_1' => 'http://thirdqq.qlogo.cn/g?b=oidb&k=qNRIKdp3wWa3eeKpPmxbaw&s=40&t=1483348873',
//                'figureurl_qq_2' => 'http://thirdqq.qlogo.cn/g?b=oidb&k=qNRIKdp3wWa3eeKpPmxbaw&s=100&t=1483348873',
//                'figureurl_qq' => 'http://thirdqq.qlogo.cn/g?b=oidb&k=qNRIKdp3wWa3eeKpPmxbaw&s=100&t=1483348873',
//                'figureurl_type' => '0',
//                'is_yellow_vip' => '0',
//                'vip' => '0',
//                'yellow_vip_level' => '0',
//                'level' => '0',
//                'is_yellow_year_vip' => '0',
//            ))
        }
    }

//    public function testAesAdd()
//    {
////        鉴爱邀请：`/web/invitate_input_record/add?rid=参数`
////
////    参数：AES加密(rid=参数，注意是用户自己的rid)
////
////    加密方式：类似Header里的加密方式；
////
////    注意事项：参数里一定不能存在空格；
////
////    例如：HOST+/web/invitate_input_record/add?token=kQToLukkYCdtIYoWhH+TMw==
//
//        $data = [
//            'rid' => '553540',
//        ];
//
//        print_r('———————————————————————————加密之前的内容———————————————————————————' . PHP_EOL);
//        print_r($data);
//
//        print_r('———————————————————————————加密之后的内容———————————————————————————' . PHP_EOL);
//        $token = IAuth::setSign($data);
//        print_r($token . PHP_EOL);
//        $token = 'Km1TdNLDPK33qSUqF1y7nA==';
//        print_r('———————————————————————————开始解密———————————————————————————' . PHP_EOL);
//        //注意token中不能存在空格，因为php的urldecode方法会把“+”替换成空格
//        $token = urldecode($token);
//        //把空格替换成“+”
//        $token = str_replace(' ', '+', $token);
//
//        // access-token AES解密
//        $result = (new Aes())->decryptWithOpenssl($token);
//        if (!empty($result))
//        {
//            //参数转换为数组
//            $array = array();
//            $paramArrs = explode('&', $result);
//            foreach ($paramArrs as $paramArr)
//            {
//                $array[strstr($paramArr, '=', true)] = substr(strstr($paramArr, '='), 1);
//            }
//            //参数赋值
////            $rid = $array['rid'];
//        }
//        print_r('———————————————————————————解密后的内容———————————————————————————' . PHP_EOL);
//        print_r($result);
//    }
//
////
//    public function test()
//    {
////        邀请添加档案的分享h5
////HOST+/web/invitate_input_record/add?token=kQToLukkYCdtIYoWhH+TMw==
////        token参数：AES加密(uid=参数 & timestamp=时间戳 & share_to=【0：微信；1：qq】)
////        加密方式：类似Header里的加密方式；
////注意事项：参数里一定不能存在空格；
////
////    例如：HOST+ /web/invitate_input_record/detail?token=gBdLZ4xY2Za00bQUeNa3WQgCLSxSOMh1NZ3sQFF/AcN2udEDTwWiztesFOiI3iqY
//
//        $data = [
//            'uid' => 10252243,
//            'timestamp' => 1574243112,
//            'share_to' => 2,
//        ];
//
//        print_r('———————————————————————————加密之前的内容———————————————————————————' . PHP_EOL);
//        print_r($data);
//
//        print_r('———————————————————————————加密之后的内容———————————————————————————' . PHP_EOL);
//        $token = IAuth::setSign($data);
//        print_r($token . PHP_EOL);
//        print_r('———————————————————————————开始解密———————————————————————————' . PHP_EOL);
//
//        $token = 'SDtJSHeqkFL71wFUmrZ9We5xoO/qtg8DAEWe0lEzxKBEbXXNjViAoASMUTiBylIU';
//
//        //注意token中不能存在空格，因为php的urldecode方法会把“+”替换成空格
//        $token = urldecode($token);
//        //把空格替换成“+”
//        $token = str_replace(' ', '+', $token);
//
//        // access-token AES解密
//        $result = (new Aes())->decryptWithOpenssl($token);
//        if (!empty($result))
//        {
//            //参数转换为数组
//            $array = array();
//            $paramArrs = explode('&', $result);
//            foreach ($paramArrs as $paramArr)
//            {
//                $array[strstr($paramArr, '=', true)] = substr(strstr($paramArr, '='), 1);
//            }
//            //参数赋值
////            $rid = $array['rid'];
//        }
//        print_r('———————————————————————————解密后的内容———————————————————————————' . PHP_EOL);
//        print_r($result);
//    }
}
